<?php

namespace app\factory;

use think\App;
use think\Container;

/**
 * ClassName:仓库存储
 * @author leijunxiang
 * @time 2024/7/20
 * @auditor
 */
class Factory
{
    //单例对象
    static private $instance;
    //仓库管理对象
    protected $registerObj;

    public function __construct()
    {
        $this->registerObj = new WarehouseManage();
    }

    public function __destruct()
    {
        $this->registerObj = null;
    }

    /**
     * 获取M层对象(类型,任意参数)
     */
    public function getModelObj($type,...$arr)
    {
        $obj = null;
        if (empty($type)) {
            return null;
        }
        //拼接对象key(类型,任意参数)
        $objKey = $this->implodeObjKey($type, $arr);

        //判断容器中是否存在类及标识
        $flag = Container::getInstance()->has($objKey);
        if ($flag) {
            $obj = app($objKey);
        }
        if (empty($obj)) {
//            //拆分对象key
//            $typeKey = $this->splitObjKey($objKey);
            //获取常驻M层对象(对象key)
            $obj = $this->registerObj->getResidentModelObj($objKey,$type);
        }
        if (empty($obj)) {
            //拆分对象key
            $typeKey = $this->splitObjKey($objKey);
            //获取m层对象(对象key)
            $obj = $this->registerObj->getModelObj($objKey,$typeKey);
        }
        return $obj;
    }

    /**
     * 获取工具对象(类型,任意参数)
     */
    public function getToolObj($type,...$arr)
    {
        $obj = null;
        if (empty($type)) {
            return null;
        }
        //拼接对象key(类型,任意参数)
        $objKey = $this->implodeObjKey($type, $arr);
        //判断容器中是否存在类及标识
        $flag = Container::getInstance()->has($objKey);
        if ($flag) {
            $obj = app($objKey);
        }
        if (empty($obj)) {
            //拆分对象key
//            $typeKey = $this->splitObjKey($objKey);
            //获取t层对象(对象key)
            $obj = $this->registerObj->getToolObj($objKey,$type);
        }

        return $obj;
    }

    /**
     * 获取单例对象
     */
    static public function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 拼接对象key(类型,任意参数)
     * @return void
     */
    public function implodeObjKey($type,$arr)
    {
        if(empty($type)){
            return "";
        }
        //拼接对象key
        if($arr){
            array_push($arr, $type);
            // 使用 `implode` 将所有参数用 `_` 进行拼接
            $objKey = implode('_', $arr);
        }else{
            $objKey = $type;
        }
        return $objKey;
    }


    /**
     * 拆分对象key
     */
    protected function splitObjKey($objKey)
    {
        $arr = explode('_', $objKey);
        return end($arr);
    }
}